import { login, logout, getInfo } from '@/api/login'


const user = {
  state: {
    name: '',
    avatar: '',
    roles: [],
    id:''
  },

  mutations: {
    SET_ID:(state,id)=>{
      state.id = id;
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit,state}, userInfo) {
      const username = userInfo.username.trim()
      return new Promise(async(resolve, reject) => {
        const data = await login(username, userInfo.password)
       
        if (!data) {
          reject('your password wrong')
        } else {
          commit('SET_ID', data.id)
          commit('SET_ROLES',data.role)
          resolve(data);
        }
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_ID', '')
          commit('SET_ROLES', [])
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
